package com.cxs.distributeddemo.component;

import com.cxs.distributeddemo.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;

/*
    add/edit contact layout
 */
public class ContactComponent extends DirectionalLayout {

    Context context;
    Component component;
    Text titleText;
    TextField nameTextField, phoneTextField;
    DialogCallback dialogCallback;

    public ContactComponent(Context context) {
        super(context);
        addComponent(context);   // 添加xml布局到组件中
        initView();
        initEvent();
    }

    /*
        修改信息时，初始化dialog
     */
    public void initData(String name, String phone) {
        if (name == null && phone == null) {
            return;
        }
        nameTextField.setText(name);
        phoneTextField.setText(phone);
        titleText.setText("修改信息");
    }
    /*
        添加xml布局到组件中
     */
    private void addComponent(Context context) {
        component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_dialog, null, false);
        // 把xml布局对象添加到自定义组件中
        super.addComponent(component);
        LayoutConfig layoutConfig = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_CONTENT);
        super.setLayoutConfig(layoutConfig);
    }

    /*
        获取子组件
            标题、姓名输入框、手机输入框
     */
    void initView() {
        titleText = (Text)component.findComponentById(ResourceTable.Id_dialog_title);
        nameTextField = (TextField)component.findComponentById(ResourceTable.Id_dialog_name);
        phoneTextField = (TextField)component.findComponentById(ResourceTable.Id_dialog_phone);
    }

    /*
        初始化单击事件
            点击确认按钮后的事件
     */
    private void initEvent() {
        component.findComponentById(ResourceTable.Id_dialog_confirm)
                .setClickedListener(c -> {
                    confirmDialog();
                });
    }

    /*
        点击确认按钮
            回调
     */
    private void confirmDialog() {
        String name = nameTextField.getText();
        String phone = phoneTextField.getText();
        if (dialogCallback != null) {
            dialogCallback.result(name, phone);
        }
    }

    /*
        设置事件回调
     */
    public void setDialogCallback(DialogCallback dialogCallback) {
        this.dialogCallback = dialogCallback;
    }

    public interface DialogCallback {
        void result(String name, String phone);
    }
}
